import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useGameStore = defineStore('game', () => {
  // 状态
  const currentRoom = ref(null)
  const currentPlayer = ref(null)
  const players = ref([])
  const gameStatus = ref('waiting') // waiting, playing, paused, finished
  const remainingTime = ref(0)
  const gameDuration = ref(180) // 游戏时长（秒），默认3分钟
  const gameTimer = ref(null)
  const connectionStatus = ref('disconnected') // disconnected, connecting, connected
  const errorMessage = ref('')
  const canvasData = ref(new Map()) // 存储画布像素数据
  const lastPaintAction = ref(null) // 最后一次涂色操作

  // 计算属性
  const isHost = computed(() => {
    if (!currentRoom.value || !currentPlayer.value) {
      console.log('isHost check failed: room or player not set')
      return false
    }
    const isHostResult = currentRoom.value.createdBy === currentPlayer.value.id
    console.log('isHost check:', {
      createdBy: currentRoom.value.createdBy,
      currentPlayerId: currentPlayer.value.id,
      isHost: isHostResult
    })
    return isHostResult
  })

  const sortedPlayers = computed(() => {
    return [...players.value].sort((a, b) => {
      // 按面积降序排列
      const areaA = a.area || 0
      const areaB = b.area || 0
      if (areaA !== areaB) {
        return areaB - areaA
      }
      // 面积相同时按加入时间排序
      return new Date(a.joinedAt) - new Date(b.joinedAt)
    })
  })

  const winner = computed(() => {
    if (gameStatus.value?.toLowerCase() !== 'finished') return null
    return sortedPlayers.value[0]
  })

  const canStartGame = computed(() => {
    return gameStatus.value?.toLowerCase() === 'waiting' &&
      players.value.length >= 2
  })

  // 动作
  const setCurrentRoom = (room) => {
    currentRoom.value = room
  }

  const setCurrentPlayer = (player) => {
    currentPlayer.value = player
  }

  const setPlayers = (playerList) => {
    players.value = playerList
  }

  const addPlayer = (player) => {
    const existingIndex = players.value.findIndex(p => p.id === player.id)
    if (existingIndex >= 0) {
      players.value[existingIndex] = player
    } else {
      players.value.push(player)
    }
  }

  const removePlayer = (playerId) => {
    const index = players.value.findIndex(p => p.id === playerId)
    if (index >= 0) {
      players.value.splice(index, 1)
    }
  }

  const updatePlayerArea = (playerId, area) => {
    const player = players.value.find(p => p.id === playerId)
    if (player) {
      player.area = area
    }
  }

  const setGameStatus = (status) => {
    gameStatus.value = status

    // 清理定时器
    if (gameTimer.value) {
      clearInterval(gameTimer.value)
      gameTimer.value = null
    }

    // 游戏开始时启动倒计时
    if (status?.toLowerCase() === 'playing' && currentRoom.value) {
      startGameTimer()
    }
    
    // 如果游戏结束，清理画布数据
    if (status?.toLowerCase() === 'finished') {
      canvasData.value.clear()
    }
  }

  const setRemainingTime = (time) => {
    remainingTime.value = time
  }

  const setGameDuration = (duration) => {
    console.log('Setting game duration in store:', duration)
    gameDuration.value = duration
  }

  const startGameTimer = () => {
    if (gameTimer.value) {
      clearInterval(gameTimer.value)
    }

    // 使用房间的实际游戏时长
    const duration = gameDuration.value
    console.log('Starting game timer with duration:', duration)
    remainingTime.value = duration

    gameTimer.value = setInterval(() => {
      if (remainingTime.value > 0) {
        remainingTime.value--
      } else {
        // 游戏时间到
        setGameStatus('finished')
      }
    }, 1000)
  }

  const setConnectionStatus = (status) => {
    connectionStatus.value = status
  }

  const setErrorMessage = (message) => {
    errorMessage.value = message
    // 3秒后自动清除错误信息
    setTimeout(() => {
      errorMessage.value = ''
    }, 3000)
  }

  // 画布数据管理
  const updateCanvasPixel = (x, y, color) => {
    const key = `${x},${y}`
    canvasData.value.set(key, color)
  }

  const getCanvasPixel = (x, y) => {
    const key = `${x},${y}`
    return canvasData.value.get(key)
  }

  const clearCanvas = () => {
    canvasData.value.clear()
  }

  // 实时涂色同步
  const processPaintAction = (paintData) => {
    const { position, brushSize, color, areaChange } = paintData
    
    // 更新画布数据
    const radius = Math.floor(brushSize / 2)
    for (let x = position.x - radius; x <= position.x + radius; x++) {
      for (let y = position.y - radius; y <= position.y + radius; y++) {
        // 圆形画笔
        if (Math.pow(x - position.x, 2) + Math.pow(y - position.y, 2) <= Math.pow(radius, 2)) {
          updateCanvasPixel(x, y, color)
        }
      }
    }

    // 更新玩家面积
    const player = players.value.find(p => p.id === paintData.playerId)
    if (player) {
      player.area = (player.area || 0) + areaChange
    }

    lastPaintAction.value = paintData
  }

  const updatePlayerAreas = (areasMap) => {
    for (const [playerId, area] of Object.entries(areasMap)) {
      const player = players.value.find(p => p.id === playerId)
      if (player.area !== undefined) {
        player.area = area
      }
    }
  }

  const resetGame = () => {
    // 重置游戏状态
    gameStatus.value = 'waiting'
    remainingTime.value = 0

    // 重置玩家面积
    players.value.forEach(player => {
      player.area = 0
      player.rank = null
    })

    // 清理定时器
    if (gameTimer.value) {
      clearInterval(gameTimer.value)
      gameTimer.value = null
    }
  }

  const leaveRoom = () => {
    // 清理状态
    currentRoom.value = null
    currentPlayer.value = null
    players.value = []
    gameStatus.value = 'waiting'
    remainingTime.value = 0
    connectionStatus.value = 'disconnected'
    errorMessage.value = ''

    // 清理定时器
    if (gameTimer.value) {
      clearInterval(gameTimer.value)
      gameTimer.value = null
    }
  }

  return {
    // 状态
    currentRoom,
    currentPlayer,
    players,
    gameStatus,
    remainingTime,
    gameDuration,
    gameTimer,
    connectionStatus,
    errorMessage,
    canvasData,
    lastPaintAction,

    // 计算属性
    isHost,
    sortedPlayers,
    winner,
    canStartGame,

    // 动作
    setCurrentRoom,
    setCurrentPlayer,
    setPlayers,
    addPlayer,
    removePlayer,
    updatePlayerArea,
    updatePlayerAreas,
    setGameStatus,
    setRemainingTime,
    setGameDuration,
    startGameTimer,
    setConnectionStatus,
    setErrorMessage,
    resetGame,
    leaveRoom,
    
    // 画布相关
    updateCanvasPixel,
    getCanvasPixel,
    clearCanvas,
    processPaintAction
  }
})
